import { EntityManager } from "@mikro-orm/mariadb";
import BaseModel from "./base";
import { Application } from "express";
import { Book } from "../entities/Book";

export default class BookModel extends BaseModel {
  constructor(app: Application, entityName: string = "Book") {
    super(app, entityName);
  }

  async insert(data: { title: string; author: string }) {
    const book = new Book(data.title, data.author);
    const res = await this.em.persist(book).flush();
    console.log("🚀 ~ BookModel ~ insert ~ res:", res);
    return res;
  }

  async update(data: { id: number; title: string; author: string }) {
    const em = this.em;
    const book = await em.findOne(Book, data.id);
    console.log("🚀 ~ BookModel ~ update ~ book:", book);
    if (!book) return false;

    book.title = data.title;
    book.author = data.author;

    em.flush();
    return book;
  }

  async find(title: string) {
    const em = this.em;
    const books = await em.find(Book, { title });

    return books;
  }

  async del(id: number) {
    const em = this.em;
    const bookRef = em.getReference(Book, id);

    const result = await em.remove(bookRef).flush();

    return result;
  }
}
